package com.lefevre.cms.service.message.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lefevre.cms.bean.QueryResult;
import com.lefevre.cms.bean.message.Remind;
import com.lefevre.cms.mapper.RemindMapper;
import com.lefevre.cms.service.besa.DaoSupport;
import com.lefevre.cms.service.message.RemindService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.Query;
import java.util.List;

/**
 * 提醒通知
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RemindServiceImpl extends DaoSupport<Remind> implements RemindService {

    @Resource
    private RemindMapper baseMapper;

    /**
     * 保存提醒
     *
     * @param remind
     */
    public void saveRemind(Object remind) {
        baseMapper.insert((Remind) remind);
    }

    /**
     * 设置提醒设状态为已读
     *
     * @param userId             用户Id
     * @param unreadRemindIdList 提醒设Id集合
     */
    public Integer updateRemindStatus(Long userId, List<String> unreadRemindIdList) {
        return baseMapper.update(null, new LambdaUpdateWrapper<Remind>()
                .set(Remind::getStatus, 20)
                .set(Remind::getReadTimeFormat, System.currentTimeMillis())
                .in(Remind::getId, unreadRemindIdList)
                .lt(Remind::getStatus, 20));
    }

    /**
     * 软删除提醒
     *
     * @param userId   用户Id
     * @param remindId 提醒Id
     */
    public Integer softDeleteRemind(Long userId, String remindId) {
        int i = 0;
        Query query = em.createQuery("update Remind o set o.status=o.status+?1 where o.id=?2 and o.receiverUserId=?3 and o.status <?4")
                .setParameter(1, 100)
                .setParameter(2, remindId)
                .setParameter(3, userId)
                .setParameter(4, 100);
        i = query.executeUpdate();
        return i;
    }


    /**
     * 根据用户Id集合删除提醒
     *
     * @param userIdList 用户Id集合
     */
    public Integer deleteRemindByUserId(List<Long> userIdList) {
        int j = baseMapper.delete(new LambdaUpdateWrapper<Remind>().in(Remind::getReceiverUserId, userIdList));
        j += baseMapper.delete(new LambdaUpdateWrapper<Remind>().in(Remind::getSenderUserId, userIdList));
        return j;
    }

    /**
     * 还原被用户删除的提醒
     *
     * @param remindId 提醒Id
     */
    public Integer reductionRemind(String remindId) {
        Remind remind = baseMapper.selectOne(new LambdaQueryWrapper<Remind>().eq(Remind::getId, remindId).gt(Remind::getStatus, 100));
        remind.setStatus(remind.getStatus() - 100);
        return baseMapper.updateById(remind);
    }

    /**
     * 根据话题Id删除提醒
     *
     * @param topicId 话题Id
     * @return
     */
    public Integer deleteRemindByTopicId(Long topicId) {
        return baseMapper.delete(new LambdaUpdateWrapper<Remind>().eq(Remind::getTopicId, topicId));
    }

    /**
     * 根据问题Id删除提醒
     *
     * @param questionId 问题Id
     * @return
     */
    public Integer deleteRemindByQuestionId(Long questionId) {
        return baseMapper.delete(new LambdaUpdateWrapper<Remind>().eq(Remind::getQuestionId, questionId));
    }

    /**
     * 根据用户Id查询提醒分页
     *
     * @param userId     用户Id
     * @param status     状态
     * @param firstIndex 索引开始,即从哪条记录开始
     * @param maxResult  获取多少条数据
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public QueryResult<Remind> findRemindByUserId(Long userId, Integer status, int firstIndex, int maxResult) {
        QueryResult<Remind> qr = new QueryResult<>();
        LambdaQueryWrapper<Remind> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.lt(Remind::getStatus, status);
        }
        wrapper.eq(Remind::getReceiverUserId, userId);
        wrapper.orderByDesc(Remind::getSendTimeFormat);
        Page<Remind> remindPage = baseMapper.selectPage(new Page<>(firstIndex, maxResult), wrapper);

        qr.setResultlist(remindPage.getRecords());
        qr.setTotalrecord(remindPage.getTotal());
        return qr;
    }

    /**
     * 根据用户Id和提醒类型代码编号查询最新一条提醒
     *
     * @param userId   用户Id
     * @param typeCode 提醒类型代码编号
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public Remind findNewRemindByUserId(Long userId, Integer typeCode) {
        List<Remind> reminds = baseMapper.selectList(new LambdaQueryWrapper<Remind>()
                .eq(Remind::getReceiverUserId, userId)
                .eq(Remind::getTypeCode, typeCode)
                .orderByDesc(Remind::getSendTimeFormat));

        return reminds.get(0);
    }

    /**
     * 根据用户Id查询未读提醒数量
     *
     * @param userId 用户Id
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
    public Long findUnreadRemindByUserId(Long userId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Remind>().eq(Remind::getReceiverUserId, userId).eq(Remind::getStatus, 10));
    }
}
